<template>
  <div class="permissions-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <span>权限管理</span>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加权限
          </el-button>
        </div>
      </template>

      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索权限名称"
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <el-table
        :data="filteredPermissions"
        style="width: 100%"
        v-loading="loading"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="权限名称" width="200" />
        <el-table-column prop="code" label="权限代码" width="150" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button size="small" @click="showRoleDialog(row)">角色</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑权限对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      :title="isEdit ? '编辑权限' : '添加权限'"
      width="500px"
    >
      <el-form
        ref="permissionFormRef"
        :model="permissionForm"
        :rules="permissionRules"
        label-width="100px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permissionForm.name" />
        </el-form-item>
        <el-form-item label="权限代码" prop="code">
          <el-input v-model="permissionForm.code" />
        </el-form-item>
        <el-form-item label="父级权限" prop="parentId">
          <el-tree-select
            v-model="permissionForm.parentId"
            :data="permissionTree"
            :props="treeProps"
            placeholder="请选择父级权限"
            style="width: 100%"
            clearable
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="permissionForm.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="permissionForm.status" style="width: 100%">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSavePermission" :loading="saving">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 角色分配对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      title="分配角色"
      width="500px"
    >
      <el-checkbox-group v-model="selectedRoles">
        <el-checkbox
          v-for="role in allRoles"
          :key="role.id"
          :label="role.id"
        >
          {{ role.name }}
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveRoles" :loading="savingRoles">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { permissionApi } from '@/api/permission'

export default {
  name: 'Permissions',
  setup() {
    const loading = ref(false)
    const saving = ref(false)
    const savingRoles = ref(false)
    const permissions = ref([])
    const permissionTree = ref([])
    const allRoles = ref([])
    const searchKeyword = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    const permissionDialogVisible = ref(false)
    const roleDialogVisible = ref(false)
    const isEdit = ref(false)
    const currentPermission = ref(null)
    const selectedRoles = ref([])

    const permissionForm = reactive({
      name: '',
      code: '',
      parentId: null,
      description: '',
      status: 'active'
    })

    const permissionRules = {
      name: [
        { required: true, message: '请输入权限名称', trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入权限代码', trigger: 'blur' }
      ]
    }

    const treeProps = {
      children: 'children',
      label: 'name',
      value: 'id'
    }

    const filteredPermissions = computed(() => {
      if (!searchKeyword.value) return permissions.value
      return permissions.value.filter(permission => 
        permission.name.includes(searchKeyword.value) ||
        permission.code.includes(searchKeyword.value)
      )
    })

    const loadPermissions = async () => {
      loading.value = true
      try {
        // 模拟API调用
        const mockPermissions = [
          {
            id: 1,
            name: '系统管理',
            code: 'system:manage',
            description: '系统管理权限',
            status: 'active',
            createTime: '2024-01-01 10:00:00',
            children: [
              {
                id: 11,
                name: '用户管理',
                code: 'user:manage',
                description: '用户管理权限',
                status: 'active',
                createTime: '2024-01-01 10:00:00'
              },
              {
                id: 12,
                name: '角色管理',
                code: 'role:manage',
                description: '角色管理权限',
                status: 'active',
                createTime: '2024-01-01 10:00:00'
              },
              {
                id: 13,
                name: '权限管理',
                code: 'permission:manage',
                description: '权限管理权限',
                status: 'active',
                createTime: '2024-01-01 10:00:00'
              }
            ]
          },
          {
            id: 2,
            name: '教务管理',
            code: 'academic:manage',
            description: '教务管理权限',
            status: 'active',
            createTime: '2024-01-02 10:00:00',
            children: [
              {
                id: 21,
                name: '课程管理',
                code: 'course:manage',
                description: '课程管理权限',
                status: 'active',
                createTime: '2024-01-02 10:00:00'
              },
              {
                id: 22,
                name: '成绩管理',
                code: 'grade:manage',
                description: '成绩管理权限',
                status: 'active',
                createTime: '2024-01-02 10:00:00'
              }
            ]
          }
        ]
        permissions.value = mockPermissions
        permissionTree.value = mockPermissions
        total.value = mockPermissions.length
      } catch (error) {
        ElMessage.error('加载权限列表失败')
      } finally {
        loading.value = false
      }
    }

    const loadRoles = async () => {
      try {
        // 模拟角色数据
        allRoles.value = [
          { id: 1, name: '管理员' },
          { id: 2, name: '教师' },
          { id: 3, name: '学生' }
        ]
      } catch (error) {
        ElMessage.error('加载角色列表失败')
      }
    }

    const showAddDialog = () => {
      isEdit.value = false
      Object.assign(permissionForm, {
        name: '',
        code: '',
        parentId: null,
        description: '',
        status: 'active'
      })
      permissionDialogVisible.value = true
    }

    const showEditDialog = (permission) => {
      isEdit.value = true
      currentPermission.value = permission
      Object.assign(permissionForm, {
        name: permission.name,
        code: permission.code,
        parentId: permission.parentId,
        description: permission.description,
        status: permission.status
      })
      permissionDialogVisible.value = true
    }

    const showRoleDialog = (permission) => {
      currentPermission.value = permission
      selectedRoles.value = [1, 2] // 模拟已选角色
      roleDialogVisible.value = true
    }

    const handleSavePermission = async () => {
      try {
        await permissionFormRef.value.validate()
        saving.value = true
        
        if (isEdit.value) {
          ElMessage.success('权限更新成功')
        } else {
          ElMessage.success('权限创建成功')
        }
        
        permissionDialogVisible.value = false
        loadPermissions()
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        saving.value = false
      }
    }

    const handleSaveRoles = async () => {
      try {
        savingRoles.value = true
        ElMessage.success('角色分配成功')
        roleDialogVisible.value = false
      } catch (error) {
        ElMessage.error('角色分配失败')
      } finally {
        savingRoles.value = false
      }
    }

    const handleDelete = async (permission) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除权限 "${permission.name}" 吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        ElMessage.success('权限删除成功')
        loadPermissions()
      } catch {
        // 用户取消
      }
    }

    const handleSearch = () => {
      currentPage.value = 1
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      loadPermissions()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadPermissions()
    }

    onMounted(() => {
      loadPermissions()
      loadRoles()
    })

    return {
      loading,
      saving,
      savingRoles,
      permissions,
      permissionTree,
      allRoles,
      searchKeyword,
      currentPage,
      pageSize,
      total,
      permissionDialogVisible,
      roleDialogVisible,
      isEdit,
      currentPermission,
      selectedRoles,
      permissionForm,
      permissionRules,
      treeProps,
      filteredPermissions,
      showAddDialog,
      showEditDialog,
      showRoleDialog,
      handleSavePermission,
      handleSaveRoles,
      handleDelete,
      handleSearch,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.permissions-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
 